﻿var CONST_YES = "YES";
var CONST_FAIL = "NO";
var CONST_POPUP = "#pbox";
var CONST_POPUP_TITLE = "#cptitle";
var CONST_POPUP_CLOSE = "#pclose a";
var CONST_POPUP_CONTENT = "#cpcontent";
var CONST_ERROR = "1";
var months = ["Jan","Feb","Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// Declaring valid date character, minimum year and maximum year
var dtCh = "/";
var minYear = 1900;
var maxYear = 2100;

var JS_LIB = {
    jQuery: $,
    ShowOnFocus: function (id, value) {
        if ($(id).val() == value)
            $(id).val("");
    },
    ShowOnBlur: function (id, value) {
        if ($(id).val() == '')
            $(id).val(value);
    },
    alert: function (msg, title, isValid) {
        jAlert(msg, title);
        if (isValid == false) {
            $("#popup_content").removeClass("alert").addClass("confirm");
        }
    },
    px2Int: function (str) {
        return parseFloat(str.replace(/px/, ""));
    },
    setWidth: function (id) {
        if ($(id).length != 0) {
            $(id).css('width', $('#list').width() - JS_LIB.px2Int($(id).css('padding-left')) - JS_LIB.px2Int($(id).css('padding-right')));
        }
    },
    summary: function (textString, display, className) {
        $('#summary').html(textString);
        $('#summary').css('display', display);
        $('#summary').attr('class', className);
    },
    message: function (textString, display, className) {
        if ($('#systemmessage').length > 0) {
            $('#systemmessage').remove();
        }
        $('#message').html(textString);
        $('#message').css('display', display);
        $('#message').attr('class', className);

    },
    systemmessage: function (textString, display, className) {
        if ($('#message').length > 0) {
            $('#message').remove();
        }
        $('#systemmessage').html(textString);
        $('#systemmessage').css('display', display);
        $('#systemmessage').attr('class', className);
    },
    back: function () {
        history.go(-1);
        return;
    },
    redirect: function (url) {
        window.location.href = url;
        return;
    },
    refresh: function (listName) {
        JS_LIB.message('', 'none', '');
        $(listName).trigger('reloadGrid');
    },
    popup: function (url, title, w) {
        JS_LIB.summary('', 'none', '');
        $(CONST_POPUP_TITLE).html(title);
        $(CONST_POPUP_CLOSE).attr('href', 'javascript:void(0);').click(function () { JS_LIB.closePopup(); });
        $(CONST_POPUP_CONTENT).html(this.ajax(url));
        jQuery.blockUI({
            message: $(CONST_POPUP),
            css: {
                border: 'none',
                backgroundColor: 'transparent',
                opacity: 1,
                textAlign: 'left',
                top: ($(window).height() - $(CONST_POPUP).height() - 34) / 2 + 'px',
                left: ($(window).width() - w) / 2 + 'px',
                width: w + 'px'
            }
        });

        $('.blockUI').css('cursor', 'default');
    },
    showTopicDetailsPopup: function (url, title, w, functionName) {
        JS_LIB.summary('', 'none', '');
        $(CONST_POPUP_TITLE).html(title);
        $(CONST_POPUP_CLOSE).attr('onclick', functionName);
        $(CONST_POPUP_CLOSE).attr('href', 'javascript:void(0);').click(function () { stopSound("div_jp_Media"); JS_LIB.closePopup(); });
        $(CONST_POPUP_CONTENT).html(this.ajax(url));
        jQuery.blockUI({
            message: $(CONST_POPUP),
            css: {
                border: 'none',
                backgroundColor: 'transparent',
                opacity: 1,
                textAlign: 'left',
                top: ($(window).height() - $(CONST_POPUP).height() - 34) / 2 + 'px',
                left: ($(window).width() - w) / 2 + 'px',
                width: w + 'px'
            }
        });

        $('.blockUI').css('cursor', 'default');
    },
    closePopup: function () {
        jQuery.unblockUI();
    },
    msgBox: function (msg, w) {
        JS_LIB.summary('', 'none', '');
        $(CONST_POPUP_TITLE).html('TSV - thesinhvien.com.vn');
        $(CONST_POPUP_CLOSE).attr('href', 'javascript:void(0);').click(function () { jQuery.unblockUI(); });
        msg = '<div style="padding-bottom:10px;">' + msg + '</div>';
        msg += '<div style="text-align:center; margin-top:10px;"><button type="button" class="button ok" onclick="JS_LIB.closePopup()">Đóng</button></div>';
        $(CONST_POPUP_CONTENT).html(msg);
        jQuery.blockUI({
            message: $(CONST_POPUP),
            css: {
                border: 'none',
                backgroundColor: 'transparent',
                opacity: 1,
                textAlign: 'left',
                width: w + 'px'
            }
        });
        $('.blockUI').css('cursor', 'default');
    },
    // Default title: 'CRM - Corporate Resource Management'
    msgConfirmBox: function (msg, w, functionname, diaTitle) {
        JS_LIB.summary('', 'none', '');
        if (!diaTitle) {
            diaTitle = 'TSV - thesinhvien.com.vn';
        }
        $(CONST_POPUP_TITLE).html(diaTitle);
        $(CONST_POPUP_CLOSE).attr('href', 'javascript:void(0);').click(function () { jQuery.unblockUI(); });
        msg = '<div style="padding-bottom:10px;">' + msg + '</div>';
        msg += '<div style="text-align:center; margin-top:10px;">' +
            '<button type="button" class="button ok" onclick="' + functionname + '">Đồng ý</button>' +
            '<button type="button" class="button cancel" onclick="JS_LIB.closePopup()">Hủy bỏ</button></div>';
        $(CONST_POPUP_CONTENT).html(msg);
        jQuery.blockUI({
            message: $(CONST_POPUP),
            css: {
                border: 'none',
                backgroundColor: 'transparent',
                opacity: 1,
                textAlign: 'left',
                width: w + 'px'
            }
        });
        $('.blockUI').css('cursor', 'default');
    },
    ajax: function (url) {
        JS_LIB.loading();
        var result = 'System Error';
        $.ajax({
            async: false,
            cache: false,
            type: "GET",
            dataType: "html",
            timeout: 1000,
            url: url,
            success: function (msg) {
                result = msg;
            }
        });
        JS_LIB.completed();
        return result;
    },
    deletes: function (listName, colName, action) {
        JS_LIB.summary("", 'none', '');
        var checked = jQuery(listName).find("tr > td > input[type=checkbox]:checked").length;
        if (checked > 0) {
            var gr = jQuery(listName).getGridParam('selarrrow');
            var arrID = "";
            var funcname = "JS_LIB.deleteAllRows('" + listName + "','" + colName + "','" + action + "')";
            JS_LIB.msgConfirmBox('Bạn có chắc là bạn muốn xóa?', 350, funcname);
        }
        else {
            JS_LIB.msgBox("Hãy chọn dòng để xóa!", 350);
        }
    },

    getSelectedIDs: function (listName, colName) {
        JS_LIB.summary("", 'none', '');
        var checked = jQuery(listName).getGridParam('selrow');
        if (checked != null) {
            var gr = jQuery(listName).getGridParam('selarrrow');
            var arrID = "";
            var ids = $(listName).getDataIDs();
            $.each(gr, function (i, rowId) {
                if ($(ids).index(rowId) < 0) {
                    var id = $(listName).getCell(rowId, colName);
                    arrID += id + ",";
                }
            });
            return arrID;
        }
        else {
            return "";
        }
    },

    deletesMultiOptions: function (listName, colName, action) {
        JS_LIB.summary("", 'none', '');
        var checked = jQuery(listName).find("tr > td > input[type=checkbox]:checked").length;
        if (checked > 0) {
            var gr = jQuery(listName).getGridParam('selarrrow');
            var arrID = "";
            var ids = $(listName).getDataIDs();
            $.each(gr, function (i, rowId) {
                if ($(ids).index(rowId) < 0) {
                    var id = $(listName).getCell(rowId, colName[0]);
                    var role = $(listName).getCell(rowId, colName[1]);
                    arrID += id + "," + role + ":";
                }
            });
            var link = action + "/?name=" + arrID;
            JS_LIB.msgConfirmBox('Bạn có chắc là mình muốn xóa?', 350, "window.location = '" + link + "'");
        }
        else {
            JS_LIB.msgBox("Vui lòng chọn dòng muốn xóa!", 350);
        }
    },
    deleteAllRows: function (listName, colName, action) {
        var gr = jQuery(listName).getGridParam('selarrrow');
        var arrID = "";
        var ids = $(listName).getDataIDs();
        $.each(gr, function (i, rowId) {
            if ($(ids).index(rowId) < 0) {
                var id = $(listName).getCell(rowId, colName);
                if (id != false) {
                    arrID += id + ",";
                }
            }
        });
        //alert(arrID); return;
        window.location = action + "/" + arrID;
    },
    //==>Tuan.Minh.Nguyen
    setUploadImage: function (value, _src) {
        if (value != "") {
            $('#Photograph').val(value[0]);
            $("#spanPhoto").html("<div id='spanPhoto'><a id='thumb1' href='" + _src + value[0] + "' class='highslide' onclick='return hs.expand(this)'><img id='imgPhoto' src='" + _src + value[0] + "' alt='Highslide JS' title='Click to enlarge'height='100px' width='100px' /></a></div>");
            $('#btnRemoveImage').css("display", "block");
        }
    },
    setUploadImageWithSize: function (value, _src, width, height) {
        if (value != "") {
            $('#Photograph').val(value[0]);
            $("#spanPhoto").html("<div id='spanPhoto'><a id='thumb1' href='" + _src + value[0] + "' class='highslide' onclick='return hs.expand(this)'><img id='imgPhoto' src='" + _src + value[0] + "' alt='Highslide JS' title='Click to enlarge' height='" + height + "' width='" + width + "' /></a></div>");
            $('#btnRemoveImage').css("display", "block");
        }
    },
    removeImage: function (controller) {
        jQuery.ajax({
            url: "/Common/RemovePhoto",
            type: "POST",
            datatype: "json",
            data: ({
                'controller': controller,
                'image': $('#Photograph').val(),
                'id': $('#ID').val()
            }),
            success: function (mess) {
                if (mess.MsgType != 1) {
                    JS_LIB.setEmptyPhoto();
                    JS_LIB.message(mess.MsgText, 'block', 'msgSuccess');
                    $('#Photograph').val("");
                } else {
                    JS_LIB.message(mess.MsgText, 'block', 'msgError');
                }
                JS_LIB.closePopup();
            }
        })
    },
    removeImageWithSize: function (controller, width, height) {
        jQuery.ajax({
            url: "/Common/RemovePhoto",
            type: "POST",
            datatype: "json",
            data: ({
                'controller': controller,
                'image': $('#Photograph').val(),
                'id': $('#ID').val()
            }),
            success: function (mess) {
                if (mess.MsgType != 1) {
                    JS_LIB.setEmptyPhotoWithSize(width, height);
                    JS_LIB.message(mess.MsgText, 'block', 'msgSuccess');
                    $('#Photograph').val("");
                } else {
                    JS_LIB.message(mess.MsgText, 'block', 'msgError');
                }
                JS_LIB.closePopup();
            }
        })
    },
    removeCVFile: function (controller) {
        jQuery.ajax({
            url: "/Common/RemoveCV",
            type: "POST",
            datatype: "json",
            data: ({
                'controller': controller,
                'file': $('#CVFile').val(),
                'id': $('#ID').val()
            }),
            success: function (mess) {
                if (mess.MsgType != 1) {
                    JS_LIB.message(mess.MsgText, 'block', 'msgSuccess');
                    $('#CVFile').val("");
                    $('#btndownload_cv').css("display", "none");
                    $('#btnRemoveCV').css("display", "none");
                } else {
                    JS_LIB.message(mess.MsgText, 'block', 'msgError');
                }
                JS_LIB.closePopup();
            }
        })
    },
    setEmptyPhoto: function () {
        $("#spanPhoto").html("<div id='spanPhoto'><img src='/Content/Images/Common/nopic.gif' height='120px' width='120px' /></div>");
        $('#btnRemoveImage').css("display", "none");
    },
    setEmptyPhotoWithSize: function (width, height) {
        $("#spanPhoto").html("<div id='spanPhoto'><img src='/Content/Images/Common/nopic.gif' height='" + height + "' width='" + width + "' /></div>");
        $('#btnRemoveImage').css("display", "none");
    },
    setUploadCV: function (value) {
        if (value != "") {
            $('#CVFile').val(value[0]);
            $('#btndownload_cv').css("display", "block");
            $('#btnRemoveCV').css("display", "block");
        }
    },
    CheckFile: function (filename, outputname, ext) {
        jQuery.ajax({
            url: "/Common/CheckFileAvailable",
            type: "POST",
            datatype: "json",
            data: ({
                'file_path': filename
            }),
            success: function (data) {

                if (data == true) {
                    window.location = "/Common/DownloadFile?file_path=" + filename + "&output=" + outputname + "." + ext;
                }
                else {
                    JS_LIB.msgBox(data, '400');
                }
            }
        });
    },
    downLoadFile: function (file_path, output) {
        //get file extension and out an readable name
        var filename = file_path;
        var outputname = output;
        var ext = filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");

        JS_LIB.CheckFile(filename, outputname, ext);
    },
    popUpWindow: function (URLStr, parameter, namePopup) {
        JS_LIB.popup(URLStr + "&value=" + $(parameter).val(), namePopup, 470);
    },

    onKeyPress: function (e, obj, reStr, length) {
        var key = window.event ? e.keyCode : e.which;
        if (key == 8 || key == 0 || key == 32 || key == 40 || key == 41 || key == 46 || key == 45 || key == 43) return true;
        var keyChar = String.fromCharCode(key);

        var re = new RegExp(reStr);

        if (obj.value.length == length && length != '')
            return false;
        return re.test(keyChar);
    },

    ExportToExcelTemplate: function (action_url, file_path, output) {
        var numberRow = $("#list").getGridParam("records");
        if (numberRow <= 0) {
            JS_LIB.msgBox('<%= Resources.Message.E0027 %>', "300");

        } else {
            jQuery.ajax({
                url: action_url,
                type: "POST",
                datatype: "json",
                success: function (data) {
                    if (data == true) {
                        JS_LIB.downLoadFile(file_path, output);
                    }
                    else {
                        JS_LIB.msgBox(data, '400');
                    }
                }

            });
        }
    },

    onKeyUp: function (obj, type) {
        if (type == undefined || type == '')
            p = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ123456789.,";
        if (type == "Number") {
            p = "0123456789.,()-+ ";
        }
        if (type == "Char") {
            p = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ";
        }
        if (type == "Unicode") {
            p = "aáàảãạăắằẳẵặâấầẩẫậbcdđeéèẻẽẹêếềểễệfghiíìỉĩịjklnmoóòỏõọôốồổỗộơớờởỡợpqrstuúùủũụưứừửữựvwxyýỳỷỹỵz";
            p += "AÁÀẢÃẠĂẮẰẲẴẶÂẤẦẨẪẬBCDĐEÉÈẺẼẸÊẾỀỂỄỆFGHIÍÌỈĨỊJKLMNOÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢPQRSTUÚÙỦŨỤƯỨỪỬỮỰVWXYÝỲỶỸỴZ ";
        }
        s = obj.value;
        l = obj.value.length;
        i = 0;
        if (l != 0) {
            while ((i < l) && (l != 0)) {
                if (p.indexOf(obj.value.charAt(i)) == -1) {
                    if (i == (l - 1)) {

                        obj.value = obj.value.substring(0, l - 1);

                    }
                    else {
                        if (i == 0) {

                            obj.value = obj.value.substring(1, l);

                        }
                        else {

                            obj.value = obj.value.substring(0, i) + obj.value.substring(i + 1, l);

                            l = obj.value.length;
                        }
                    }
                }
                else
                    i++;
            }

        }
    },
    isPhone: function (value) {
        p = "0123456789.,()-+ ";

        s = value;
        l = value.length;
        i = 0;
        if (l != 0) {
            while ((i < l) && (l != 0)) {
                if (p.indexOf(value.charAt(i)) == -1) {
                    if (i == (l - 1))
                        return false;
                    else {
                        if (i == 0)
                            return false;
                        else {
                            return false;
                            l = value.length;
                        }
                    }
                }
                else
                    i++;
            }

        }
        return true;
    },
    compareDate: function (date1, date2) {
        var result = 0;
        if (date1 == "" || date2 == "")
            return true;

        var inputDate1 = Date.parse(convertDate(date1));
        var inputDate2 = Date.parse(convertDate(date2));
        if (inputDate1 < inputDate2)
            result = -1;
        else
            if (inputDate1 > inputDate2)
                result = 1;
            else
                result = 0;
        return result;

    },
    //==>End tuan.minh.nguyen
    /*------- phihung.nguyen ------- */
    removeMultiFile: function (file, hidField, element, table) {
        //Old Rules : Check Contract file at least 1 file
        //        if (table == "Contract") {
        //            if ($("#tbl").find("a").size() == 1) {
        //                JS_LIB.summary("Attachment File must be at least 1 file !", 'block', 'msgError');
        //                return false;
        //            }
        //        }
        $("#row_upload" + element).remove();
        var oldValue = $("#" + hidField).val();
        $("#" + hidField).val(oldValue + file + ":");
        return false;
    }
    ,
    listJR: function (page) {
        JS_LIB.popup('/Common/ListJR/?page=' + page, 'Job Request List', 1024);
    },
    clearJR: function (obj, subObj) {
        $(obj).attr('value', '');
        $(subObj).attr('value', '');
    },
    listManager: function () {
        JS_LIB.popup('/Common/ListManager', 'Manager List', 850);
    },
    clearManager: function (obj) {
        $(obj).val("");
    },

    listUniversity: function () {
        JS_LIB.popup('/Common/ListUniversity', 'University List', 850);
    },
    clearHidValue: function (obj, subObj) {
        $(obj).val("");
        $(subObj).attr('value', '');
    },
    setFilter: function (text, valProvince, valDistrict, url) {
        $.ajax({
            type: "POST",
            datatype: "json",
            url: "/danhmuc/timkiem/",
            data: ({
                text: text,
                valProvince: valProvince,
                valDistrict: valDistrict
            }),
            success: function (data) {
                window.location = url;
            }
        });
    },
    /*------- End ------- */
    /*Added by Huy.L, date: 10-21-2010*/
    /*For loading*/
    loading: function () {
        if ($("#CRMLoading") != undefined) {
            $("#CRMLoading").remove();
        }
        var top = ($(window).height() - 30) / 2 + 'px';
        var div = document.createElement('div');
        $(div).attr("id", "CRMLoading");
        $(div).css("top", top);
        $(div).html("Loading...");
        $("body").append(div);
    },
    completed: function () {
        $("#CRMLoading").fadeOut(1000, function () {
            $("#CRMLoading").remove();
        });
    },
    /*End loading*/
    onEnterKeyword: function () {
        $("#txtKeyword").keypress(function (event) {
            if (event.keyCode == 13) {
                $("#btnFilter").click();
            }
        });
    },
    format: function (source) {
        //return $.format(source, $.makeArray(arguments).slice(1));        
        if (arguments.length > 1) {
            params = $.makeArray(arguments).slice(1);
            $.each(params, function (i, n) {
                source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
            });
        }
        return source;
    }
};

//Add Focus when Search
function ShowOnFocus(id, value) {
    if ($(id).val() == value)
        $(id).val("");
}

function ShowOnBlur(id, value) {

    if ($(id).val() == '')
        $(id).val(value);
}
/*------------------------------------------------*/
//Vilidate Date

/**
* DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/
// Declaring valid date character, minimum year and maximum year
var dtCh = "/";
var minYear = 0001;
var maxYear = 9999;

function isInteger(s) {
    var i;
    for (i = 0; i < s.length; i++) {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag) {
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary(year) {
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i == 4 || i == 6 || i == 9 || i == 11) { this[i] = 30 }
        if (i == 2) { this[i] = 29 }
    }
    return this
}

function isDate(dtStr) {
    var daysInMonth = DaysArray(12)
    var pos1 = dtStr.indexOf(dtCh)
    var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
    var strDay = dtStr.substring(0, pos1)
    var strMonth = dtStr.substring(pos1 + 1, pos2)
    var strYear = dtStr.substring(pos2 + 1)
    strYr = strYear
    if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
    if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
    }
    day = parseInt(strDay)
    month = parseInt(strMonth)
    year = parseInt(strYr)
    if (pos1 == -1 || pos2 == -1) {
        return false
    }
    if (strMonth.length < 1 || month < 1 || month > 12) {
        return false

    }
    if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
        return false

    }
    if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
        return false

    }
    if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
        return false
    }
    return true
}
function convertDate(dtStr) {
    var result;
    var daysInMonth = DaysArray(12)
    var pos1 = dtStr.indexOf(dtCh)
    var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
    var strDay = dtStr.substring(0, pos1)
    var strMonth = dtStr.substring(pos1 + 1, pos2)
    var strYear = dtStr.substring(pos2 + 1)
    strYr = strYear
    if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
    if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
    }
    day = parseInt(strDay)
    month = parseInt(strMonth)
    year = parseInt(strYr)
    result = year + '/' + month + '/' + day
    return result
}

function convertDateDB(dtStr) {
    var result;
    var daysInMonth = DaysArray(12)
    var pos1 = dtStr.indexOf(dtCh)
    var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
    var strDay = dtStr.substring(0, pos1)
    var strMonth = dtStr.substring(pos1 + 1, pos2)
    var strYear = dtStr.substring(pos2 + 1)
    strYr = strYear
    if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
    if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
    }
    day = parseInt(strDay)
    month = parseInt(strMonth)
    year = parseInt(strYr)
    result = month + '/' + day + '/' + year
    return result
}

//phi hung nguyen
var row_upload_id = 0;
//Remove Row Upload
function RemoveRow(object) {
    var index = $(object).attr("id");
    $("#row_upload" + index + "").remove();
    return false;
}

function AddRowUpload(y) {
    if (y != undefined) {
        if (row_upload_id < y) {
            row_upload_id = y;
        }
    }
    $("#tbl").append("<tr id='row_upload" + row_upload_id + "'>" +
    "<td class='label' style='width: 180px;'>Attachment</td>" +
    "<td id='contentFile' class='input'>" +
        "<input type='file' name='file'/>" +
    "</td>" +
    "<td valign='top'>" +
        "<button type='button' id='" + row_upload_id + "' class='icon minus' onclick='return RemoveRow(this);'  title='Remove'></button>" +
    "</td></tr>");
    row_upload_id++;
    return false;
}

/*Added by Tai Nguyen*/
function getJqgridSelectedRows(gridName) {
    var result = "";
    $.each($(gridName + " tr"), function () {
        var isChecked = $(this).find("td > input[type=checkbox]").attr("checked");
        if (isChecked) {
            result += $(this).attr("id") + ",";
        }
    });
    return result.length == 0 ? "" : result.substring(0, result.length - 1);
}


function getJqgridSelectedIDs(listName, colName) {  
    JS_LIB.summary("", 'none', '');
    var gr = getJqgridSelectedRows(listName).split(",");
    var arrID = "";
    var ids = $(listName).getDataIDs();
    $.each(gr, function (i, rowId) {
        if ($(ids).index(rowId) < 0) {
            var id = $(listName).getCell(rowId, colName);
            arrID += id + ",";
        }
    });
    return arrID;
}
/*PTOAdmin*/
var sDateOffTableSelector = "#tblDateOff";
var sDateOffInputNamePrefix = "txtDateOff_";
var sDateOffInputSelector = "input[name^='" + sDateOffInputNamePrefix + "']";
var sHoursInputNamePrefix = "txtHours_";
var sHoursInputSelector = "input[name^='" + sHoursInputNamePrefix + "']";
var ptoType = {
    Hour:0,
    Date:1
}
function disableAllControl() {
    $(sDateOffTableSelector + " tr").find("*").attr("disabled", "disabled");
    $(sDateOffTableSelector + " tr").find("*").datepicker("disable");
}
function enableAllControl() {
    $(sDateOffTableSelector + " tr").find("*").removeAttr("disabled");
    $(sDateOffTableSelector + " tr").find("*").datepicker("enable");
}
function ptoTypeOf(typeID) {
    var hourTypeID_Arr = $("#hidPTO_TypeIDs_IsHour").val().split(',');
    if ($.inArray(typeID, hourTypeID_Arr) > -1)
        return ptoType.Hour;
    return ptoType.Date;
}
function addDateOff() {
    var row = createNewRow(ptoType.Hour);
    $(sDateOffTableSelector).append(row);
    setNumberOfDateOff();
    setLastRowValidation(ptoType.Hour);
}
function removeDateOff() {
    if ($(sDateOffTableSelector + " tr").length > 1) {
        $(sDateOffTableSelector + " tr:last").remove();
        setNumberOfDateOff();
    }
}
function setLastRowValidation(type) {
    setRowValidation($(sDateOffTableSelector + " tr:last"),type);
}
function setRowValidation(row,type) {
    if (type == ptoType.Hour) {
        $(row).find(sDateOffInputSelector).datepicker();
        $(row).find(sDateOffInputSelector).rules("add",
                    { required: true, checkDate: true });
        $(row).find(sHoursInputSelector).rules("add",
                    { required: true, number: true, min: 1, max: 8 });
    }
    else {
        $(row).find('#txtDateOffFrom').rules("add",
                    { required: true, checkDate: true });
        $(row).find('#txtDateOffTo').rules("add",
                    { required: true, checkDate: true });
        $(row).find('#txtDateOffFrom').datepicker();
        $(row).find('#txtDateOffTo').datepicker();
    }
}
function createNewRow(type) {
    var row = "";
    if (type == ptoType.Hour) {
        var numRow = $(sDateOffTableSelector + " tr").length + 1;
        var newDateInputId = sDateOffInputNamePrefix + numRow;
        var newHoursInputId = sHoursInputNamePrefix + numRow;
        row += "<tr>";
        row += "<td class='label required'>Date</td>";
        row += "<td class='input datetimecell'><input maxlength='10' name='" + newDateInputId +
                    "' class='datetime' type='text' id='" + newDateInputId + "'/></td>";
        row += "<td class='label required' style='width:50px'>Hour(s)</td>";
        row += "<td class='input'><input style='width:20px' name='" + newHoursInputId +
                    "' type='text' id='" + newHoursInputId + "'/></td>"
        row += "<td>"
        if (numRow == 1) {
            row += " <button id='btnAddDateOff' type='button' class = 'icon plus'" +
                     " onclick='addDateOff()' /> ";
            row += "<button id='btnRemoveDateOff' type='button' class = 'icon minus'" +
                     " onclick='removeDateOff()' />";
        }
        row += "</td></tr>";
    }
    else {
        row = createNotHourTypeRow();
    }
    return row;
}
function createNotHourTypeRow() {
    var objRow = "" +
                "<tr>" +
                    "<td class='label required'>" +
                        "From Date<span>*</span>" +
                    "</td>" +
                    "<td class='input datetimecell'>" +
                        "<input type='text' id='txtDateOffFrom' name='txtDateOffFrom' class='datetime' maxlength='10'/>" +
                    "</td>" +
                    "<td class='label required'>" +
                        "To Date<span>*</span>" +
                    "</td>" +
                    "<td class='input datetimecell'>" +
                        "<input type='text' id='txtDateOffTo' name='txtDateOffTo' class='datetime' maxlength='10'/>" +
                    "</td>" +
                "</tr>";
    return objRow;
}
function setInputDateOffType(type) {
    $("#hidPTO_Type").val(type);
    $(sDateOffTableSelector).html("");
    $(sDateOffTableSelector).html(createNewRow(type));
    setLastRowValidation(type);
};
function setNumberOfDateOff() {
    $("#hidNumberOfDateOff").val($(sDateOffTableSelector + " tr").length);
}
/*End PTOAdmin*/

/*End Tai Nguyen*/

function AddMonth(controlId, strDate, month) {
    strDate = strDate.replace("-", "/");
    var str = strDate.split('/');
    var curMon = str[0];
    var year = str[1];
    curMon = new Date(curMon + " 01, 1900").getMonth() + 1;    
    strDate = year + "/" + curMon + "/1";    
    date = new Date(strDate);    
    date.setMonth(date.getMonth()+ month);    
    $("#" + controlId).val(months[date.getMonth()] + "-" + date.getFullYear());
}

function CurMonth(controlId) {
    var date = new Date();
    $("#" + controlId).val(months[date.getMonth()] + "-" + date.getFullYear());
}